package com.sy.vedio.controller;

import com.sy.utils.MD5Utils;
import com.sy.utils.Result;
import com.sy.vedio.pojo.Users;
import com.sy.vedio.pojo.vo.UsersVO;
import com.sy.vedio.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * 注册和登录
 */
@RestController
public class RegisterLoginController extends BasicController {

	@Autowired
	private UserService userService;

	/**
	 * 设置用户的redis-session
	 * @param userModel
	 * @return
	 */
	public UsersVO setUserRedisSessionToken(Users userModel) {
		String uniqueToken = UUID.randomUUID().toString();
		// 添加冒号来实现分类
		redis.set(USER_REDIS_SESSION + ":" + userModel.getId(), uniqueToken, 1000 * 60 * 30);

		UsersVO userVO = new UsersVO();
		BeanUtils.copyProperties(userModel, userVO);
		userVO.setUserToken(uniqueToken);
		return userVO;
	}
	
	@PostMapping("/register")
	public Result register(@RequestBody Users users) throws Exception {


		// 1、判断用户名密码是否为空
		if (StringUtils.isBlank(users.getUsername()) || StringUtils.isBlank(users.getUsername())) {
			return Result.errorMsg("用户名密码不能为空");
		}

		// 2、判断用户是否存在
		boolean isUser = userService.isUserExist(users.getUsername());

		// 3、保存用户信息
		if (!isUser) {
			users.setNickname(users.getUsername());  // 昵称
			users.setPassword(MD5Utils.getMD5Str(users.getPassword()));  // 设置MD5加密后的密码
			users.setFansCounts(0);
			users.setReceiveLikeCounts(0);
			users.setFollowCounts(0);
			userService.saveUser(users);
		} else {
			return Result.errorMsg("用户名已经存在");
		}

		users.setPassword("");

		UsersVO userVO = setUserRedisSessionToken(users);

		return Result.ok(userVO);
	}


	@PostMapping("/login")
	public Result login(@RequestBody Users user) throws Exception {
		String username = user.getUsername();
		String password = user.getPassword();

//		Thread.sleep(3000);  // 故意让前端转3秒圈

		// 1. 判断用户名和密码必须不为空
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return Result.ok("用户名或密码不能为空...");
		}

		// 2. 判断用户是否存在
		Users userResult = userService.queryUserForLogin(username,
				MD5Utils.getMD5Str(user.getPassword()));

		// 3. 返回
		if (userResult != null) {
			userResult.setPassword("");
			UsersVO userVO = setUserRedisSessionToken(userResult);
			return Result.ok(userVO);
		} else {
			return Result.errorMsg("用户名或密码不正确, 请重试...");
		}
	}


	@PostMapping("/logout")
	public Result logout(String userId) throws Exception {
		redis.del(USER_REDIS_SESSION + ":" + userId);
		return Result.ok();
	}
}
